<template>
  <el-config-provider :locale="zhCn">
    <div class="customer-management">
      <!-- 筛选条件区域 -->
      <filter-form v-model="filterForm" :form-items="formItems" @search="handleSearch" @reset="resetFilter" @update:modelValue="handleFilterChange" />

      <!-- 操作按钮区域 -->
      <div class="operation-section">
        <el-button type="primary" @click="handleGenerateReport" :loading="generateLoading"> 生成报告 </el-button>
      </div>

      <!-- 报告展示区域 -->
      <div class="report-document-section" v-loading="loading || generateLoading">
        <div class="report-content" v-if="reportData && reportData.data">
          <!-- 使用稳定的手动渲染 -->
          <div class="markdown-content" v-html="fallbackRenderedMarkdown"></div>
        </div>
        <div class="report-content empty-state" v-else>
          <el-empty description="暂无报告数据，请选择条件并生成报告" />
        </div>
        <div class="report-actions" v-if="reportData && reportData.data">
          <el-button type="primary" @click="handleDownload">下载报告</el-button>
          <!-- <el-button type="danger" @click="handleDelete">删除报告</el-button> -->
        </div>
      </div>
    </div>
  </el-config-provider>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import FilterForm from '@/components/FilterForm/index.vue';
import type { FormItem } from '@/components/FilterForm/index.vue';
import { selectGenerateReport, generateReport, deleteReport } from '@/api/userMange/generateReport';
import type { SelectGenerateReportParams, GenerateReportParams } from '@/api/userMange/generateReport';
import MarkdownIt from 'markdown-it';

interface ReportItem {
  id: number;
  account_type: string;
  data: string;
  time: string;
  type: string;
  wx_id: string;
}

// 从本地存储获取wxId
const wxId = ref(localStorage.getItem('msgprofile') ? JSON.parse(localStorage.getItem('msgprofile')!).wx_id : '');

// 初始化 MarkdownIt 实例作为备用方案
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  breaks: true
});

// 筛选表单
const filterForm = reactive({
  type: '',
  timeRange: []
});

// 表单项配置
const formItems = computed<FormItem[]>(() => [
  {
    label: '报告类型',
    prop: 'type',
    type: 'select',
    placeholder: '请选择报告类型',
    options: [
      { label: '公司', value: '1' },
      { label: '部门', value: '2' },
      { label: '个人', value: '3' }
    ]
  },
  {
    label: '时间范围',
    prop: 'timeRange',
    type: 'daterange',
    placeholder: '请选择时间范围',
    valueFormat: 'YYYY-MM-DD'
  }
]);

// 报告数据
const reportData = ref<ReportItem | null>(null);
const loading = ref(false);
const generateLoading = ref(false);

// 获取报告类型文本
const getReportTypeText = (type: string | number) => {
  const textMap: Record<string, string> = {
    '1': '公司',
    '2': '部门',
    '3': '个人'
  };
  return textMap[String(type)] || '未知';
};

// 处理 Markdown 内容 - 现在仅用于调试
const processedMarkdownContent = computed(() => {
  if (!reportData.value?.data) {
    return '';
  }

  let markdownContent = reportData.value.data;

  // 如果数据被 ```markdown 代码块包装，提取内容
  if (markdownContent.startsWith('```markdown\n') && markdownContent.endsWith('```')) {
    markdownContent = markdownContent.slice(12, -3);
  }

  // 如果数据已经是 Markdown 格式，直接返回
  if (isMarkdownFormat(markdownContent)) {
    return markdownContent;
  }

  // 如果是纯文本，转换为 Markdown 格式
  return convertToMarkdown(markdownContent);
});

// 备用渲染方案
const fallbackRenderedMarkdown = computed(() => {
  if (!reportData.value?.data) {
    return '';
  }

  let markdownContent = reportData.value.data;

  // 如果数据被 ```markdown 代码块包装，提取内容
  if (markdownContent.startsWith('```markdown\n') && markdownContent.endsWith('```')) {
    markdownContent = markdownContent.slice(12, -3);
  }

  // 如果数据已经是 Markdown 格式，直接渲染
  if (isMarkdownFormat(markdownContent)) {
    return md.render(markdownContent);
  }

  // 如果是纯文本，转换为 Markdown 格式后渲染
  const convertedMarkdown = convertToMarkdown(markdownContent);
  return md.render(convertedMarkdown);
});

// 检查是否为 Markdown 格式
const isMarkdownFormat = (text: string): boolean => {
  const markdownPatterns = [
    /^#{1,6}\s+/m, // 标题
    /^\*\*.*\*\*/m, // 粗体
    /^\*.*\*/m, // 斜体
    /^[-*+]\s+/m, // 列表
    /^\d+\.\s+/m, // 有序列表
    /^\|.*\|/m, // 表格
    /^```/m, // 代码块
    /^>/m // 引用
  ];

  return markdownPatterns.some((pattern) => pattern.test(text));
};

// 将纯文本转换为 Markdown 格式
const convertToMarkdown = (text: string): string => {
  let markdown = text;

  // 转换标题（基于行首的数字或特殊字符）
  markdown = markdown.replace(/^(\d+[\.、]?\s*[^\n]*?)$/gm, '## $1');

  // 转换列表项（基于行首的 - 或 * 或数字）
  markdown = markdown.replace(/^[-*•]\s*(.+)$/gm, '- $1');
  markdown = markdown.replace(/^(\d+)[\.、]\s*(.+)$/gm, '$1. $2');

  // 转换粗体（基于【】或强调词）
  markdown = markdown.replace(/【([^】]+)】/g, '**$1**');
  markdown = markdown.replace(/(\s|^)(总计|合计|小计|统计|汇总)(\s*[:：])/g, '$1**$2**$3');

  // 转换表格（基于制表符或多个空格分隔的数据）
  const lines = markdown.split('\n');
  const processedLines = [];
  let inTable = false;

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim();

    // 检查是否为表格行（包含多个制表符或连续空格分隔的数据）
    if (line && (line.includes('\t') || /\s{2,}/.test(line))) {
      const cells = line.split(/\t|\s{2,}/).filter((cell) => cell.trim());

      if (cells.length >= 2) {
        if (!inTable) {
          // 添加表格头
          processedLines.push('| ' + cells.join(' | ') + ' |');
          processedLines.push('| ' + cells.map(() => '---').join(' | ') + ' |');
          inTable = true;
        } else {
          // 添加表格行
          processedLines.push('| ' + cells.join(' | ') + ' |');
        }
        continue;
      }
    }

    inTable = false;
    processedLines.push(line);
  }

  markdown = processedLines.join('\n');

  // 添加分隔线
  markdown = markdown.replace(/^={3,}$/gm, '\n---\n');
  markdown = markdown.replace(/^-{3,}$/gm, '\n---\n');

  // 转换代码块（基于缩进）
  markdown = markdown.replace(/^(\s{4,})(.+)$/gm, '```\n$2\n```');

  return markdown;
};

// 搜索处理
const handleSearch = () => {
  fetchReportList();
};

// 重置筛选
const resetFilter = () => {
  Object.assign(filterForm, {
    type: '',
    timeRange: []
  });
  fetchReportList();
};

// 筛选条件变化
const handleFilterChange = (newValue: any) => {
  console.log('筛选条件变化:', newValue);
  // 更新本地筛选表单数据
  Object.assign(filterForm, newValue);
  console.log('更新后的筛选表单:', filterForm);
};

// 获取报告数据
const fetchReportList = async () => {
  loading.value = true;
  try {
    console.log('当前筛选表单数据:', filterForm);

    const params: SelectGenerateReportParams = {};

    // 只有当type不为空字符串时才传递
    if (filterForm.type && filterForm.type !== '') {
      params.type = filterForm.type;
    }

    // 处理时间范围
    if (filterForm.timeRange && filterForm.timeRange.length === 2) {
      // 由于已设置 valueFormat: 'YYYY-MM-DD'，直接使用返回的字符串
      params.startTime = filterForm.timeRange[0];
      params.endTime = filterForm.timeRange[1];
    }

    // 传递微信ID
    if (wxId.value) {
      params.myWxId = wxId.value;
    }

    console.log('获取报告数据，最终传递参数:', params);

    const response = await selectGenerateReport(params);
    if (response.code === 200) {
      reportData.value = response.data;
    } else {
      ElMessage.error(response.msg || '获取报告失败');
      reportData.value = null;
    }
  } catch (error) {
    console.error('获取报告失败:', error);
    ElMessage.error('获取报告失败');
    reportData.value = null;
  } finally {
    loading.value = false;
  }
};

// 生成报告
const handleGenerateReport = async () => {
  if (!filterForm.type || filterForm.type === '') {
    ElMessage.warning('请选择报告类型');
    return;
  }
  if (!filterForm.timeRange || filterForm.timeRange.length !== 2) {
    ElMessage.warning('请选择时间范围');
    return;
  }

  generateLoading.value = true;
  try {
    // 由于已设置 valueFormat: 'YYYY-MM-DD'，直接使用返回的字符串
    const params: GenerateReportParams = {
      type: filterForm.type,
      startTime: filterForm.timeRange[0],
      endTime: filterForm.timeRange[1],
      myWxId: wxId.value
    };

    console.log('生成报告参数:', params);

    const response = await generateReport(params);
    if (response.code === 200) {
      ElMessage.success('报告生成成功');
      fetchReportList();
    } else {
      ElMessage.error(response.msg || '生成报告失败');
    }
  } catch (error) {
    console.error('生成报告失败:', error);
    ElMessage.error('生成报告失败');
  } finally {
    generateLoading.value = false;
  }
};

// 下载报告
const handleDownload = async () => {
  if (!reportData.value) {
    ElMessage.warning('暂无报告可下载');
    return;
  }

  try {
    let downloadContent = reportData.value.data;
    let fileExtension = 'txt';

    // 如果数据被 ```markdown 代码块包装，提取内容
    if (downloadContent.startsWith('```markdown\n') && downloadContent.endsWith('```')) {
      downloadContent = downloadContent.slice(12, -3); // 移除 ```markdown\n 和 ```
      fileExtension = 'md';
    } else if (isMarkdownFormat(downloadContent)) {
      // 如果是 Markdown 格式
      fileExtension = 'md';
    } else {
      // 如果数据不是 Markdown 格式，转换为 Markdown
      downloadContent = convertToMarkdown(downloadContent);
      fileExtension = 'md';
    }

    // 创建下载链接
    const blob = new Blob([downloadContent], { type: 'text/markdown;charset=utf-8' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `报告_${reportData.value.id}_${reportData.value.time}.${fileExtension}`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    ElMessage.success('下载成功');
  } catch (error) {
    console.error('下载失败:', error);
    ElMessage.error('下载失败');
  }
};

// 删除报告
const handleDelete = async () => {
  if (!reportData.value) {
    ElMessage.warning('暂无报告可删除');
    return;
  }

  try {
    await ElMessageBox.confirm('确定要删除这个报告吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await deleteReport(String(reportData.value.id));
    if (response.code === 200) {
      ElMessage.success('删除成功');
      reportData.value = null;
    } else {
      ElMessage.error(response.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除报告失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchReportList();
});
</script>

<style lang="scss" scoped>
.customer-management {
  padding: 24px;
  min-height: 100vh;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;

  .operation-section {
    // margin: 20px 0;
    // padding: 24px;
    // background: white;
    // border-radius: 12px;
    // box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
    // border: 1px solid rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(10px);

    .el-button {
      padding: 12px 24px;
      font-size: 14px;
      font-weight: 500;
      // border-radius: 8px;
      transition: all 0.3s ease;

      // &.el-button--primary {
      //   background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      //   border: none;
      //   box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);

      //   &:hover {
      //     transform: translateY(-2px);
      //     box-shadow: 0 8px 25px rgba(102, 126, 234, 0.6);
      //   }
      // }
    }
  }

  .report-document-section {
    background: white;
    border-radius: 8px;
    padding: 0;
    box-shadow: 0 12px 48px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.3);
    overflow: hidden;
    margin-top: 20px;

    .report-header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 32px;
      position: relative;

      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="white" opacity="0.1"/><circle cx="75" cy="75" r="1" fill="white" opacity="0.1"/><circle cx="50" cy="10" r="0.5" fill="white" opacity="0.05"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
        pointer-events: none;
      }

      h2 {
        margin: 0 0 24px 0;
        font-size: 28px;
        font-weight: 600;
        letter-spacing: -0.5px;
        position: relative;
        z-index: 1;
      }

      .report-meta {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 16px;
        position: relative;
        z-index: 1;

        p {
          margin: 0;
          padding: 12px 16px;
          background: rgba(255, 255, 255, 0.15);
          border-radius: 8px;
          backdrop-filter: blur(10px);
          border: 1px solid rgba(255, 255, 255, 0.2);
          font-size: 14px;

          strong {
            font-weight: 600;
            margin-right: 8px;
          }
        }
      }
    }

    .report-content {
      padding: 40px;

      &.empty-state {
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 300px;
      }

      .markdown-content {
        background: #f8f9fa;
        border: 1px solid #e9ecef;
        border-radius: 12px;
        padding: 32px;
        font-size: 14px;
        line-height: 1.8;
        color: #2d3748;
        margin: 0;
        box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.05);
        position: relative;

        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          width: 4px;
          height: 100%;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          border-radius: 0 2px 2px 0;
        }

        // 覆盖组件默认样式，保持我们的设计
        :deep(h1),
        :deep(h2),
        :deep(h3),
        :deep(h4),
        :deep(h5),
        :deep(h6) {
          margin: 24px 0 16px 0;
          font-weight: 600;
          line-height: 1.4;
          color: #1a202c;

          &:first-child {
            margin-top: 0;
          }
        }

        :deep(h1) {
          font-size: 28px;
          border-bottom: 2px solid #e2e8f0;
          padding-bottom: 12px;
        }

        :deep(h2) {
          font-size: 24px;
          border-bottom: 1px solid #e2e8f0;
          padding-bottom: 8px;
        }

        :deep(table) {
          width: 100%;
          border-collapse: collapse;
          margin: 24px 0;
          background: white;
          border-radius: 8px;
          overflow: hidden;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

          th,
          td {
            padding: 12px 16px;
            text-align: left;
            border-bottom: 1px solid #e2e8f0;
          }

          th {
            background: #f7fafc;
            font-weight: 600;
            color: #2d3748;
            border-bottom: 2px solid #e2e8f0;
          }

          tr:hover {
            background: #f7fafc;
          }
        }

        :deep(blockquote) {
          margin: 24px 0;
          padding: 16px 20px;
          background: #f0f4f8;
          border-left: 4px solid #4299e1;
          border-radius: 0 8px 8px 0;
          font-style: italic;
          color: #2d3748;
        }

        :deep(pre) {
          background: #2d3748;
          color: #e2e8f0;
          padding: 20px;
          border-radius: 8px;
          overflow-x: auto;
          margin: 24px 0;
        }

        :deep(strong) {
          font-weight: 600;
          color: #2d3748;
        }
      }
    }

    .report-actions {
      padding: 24px 40px 40px;
      display: flex;
      gap: 16px;
      justify-content: flex-end;
      border-top: 1px solid #f1f3f4;
      background: #fafbfc;

      .el-button {
        padding: 12px 24px;
        font-size: 14px;
        font-weight: 500;
        // border-radius: 8px;
        transition: all 0.3s ease;

        &.el-button--primary {
          // background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
          // border: none;
          // box-shadow: 0 4px 15px rgba(72, 187, 120, 0.4);

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(72, 187, 120, 0.6);
          }
        }

        &.el-button--danger {
          background: linear-gradient(135deg, #f56565 0%, #e53e3e 100%);
          border: none;
          color: white;
          box-shadow: 0 4px 15px rgba(245, 101, 101, 0.4);

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(245, 101, 101, 0.6);
          }
        }
      }
    }
  }

  .empty-report {
    background: white;
    border-radius: 8px;
    padding: 60px 40px;
    box-shadow: 0 12px 48px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.3);
    text-align: center;
    margin-top: 24px;

    .el-empty {
      padding: 40px 0;

      :deep(.el-empty__image) {
        width: 120px;
        height: 120px;

        svg {
          width: 100%;
          height: 100%;
          color: #cbd5e0;
        }
      }

      :deep(.el-empty__description) {
        font-size: 16px;
        color: #718096;
        margin-top: 24px;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .customer-management {
    padding: 16px;

    .operation-section {
      padding: 20px;
    }

    .report-document-section {
      .report-header {
        padding: 24px 20px;

        h2 {
          font-size: 24px;
        }

        .report-meta {
          grid-template-columns: 1fr;
        }
      }

      .report-content {
        padding: 24px 20px;

        pre {
          padding: 20px;
          font-size: 13px;
        }
      }

      .report-actions {
        padding: 20px;
        flex-direction: column;

        .el-button {
          width: 100%;
        }
      }
    }

    .empty-report {
      padding: 40px 20px;
    }
  }
}

// 动画效果
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.report-document-section {
  animation: fadeInUp 0.6s ease-out;
}

.empty-report {
  animation: fadeInUp 0.6s ease-out;
}
</style>
